//
//  LeftOrderVC.m
//  Ufan
//
//  Created by yangqingluo on 15/11/29.
//  Copyright © 2015年 yangqingluo. All rights reserved.
//

#import "LeftOrderVC.h"
#import "OrderCell.h"
#import "LeftOrderPayVC.h"
#import "XHRefreshControl.h"
#import "OrderDetailVC.h"

@interface LeftOrderVC ()<UITableViewDataSource,UITableViewDelegate,XHRefreshControlDelegate>{
    int currentPage;
    int pageCount;
}

@property (nonatomic, strong) NSString *sureOrderID;
@property (nonatomic, strong) UITableView *showTableView;
@property (nonatomic, strong) NSMutableArray *datasource;
@property (nonatomic, strong) XHRefreshControl *refreshControl;
@end

@implementation LeftOrderVC

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if (!self.showTableView.superview) {
        [self.view addSubview:self.showTableView];
    }
    
    if ([AppPublic shareInstanceApp].needRefreshOrderList) {
        [self.refreshControl startPullDownRefreshing];
        [AppPublic shareInstanceApp].needRefreshOrderList = NO;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = RGBA(245, 245, 245, 1.0);
    [self setupBarButtonItem];
    
    
}

- (void)setupBarButtonItem{
    self.title = @"我的订单";
    
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 64, 44)];
    [backButton setImage:[UIImage imageNamed:@"nav_back.png"] forState:UIControlStateNormal];
    [backButton setImageEdgeInsets:UIEdgeInsetsMake(12, 0, 12, 48)];
    backButton.tag = 988;
    [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    [self.navigationItem setLeftBarButtonItem:backItem];
}

#pragma response
- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo{
    if ([eventName isEqualToString:UF_Router_Event_OrderPay]) {
        LeftOrderPayVC *payVC = [[LeftOrderPayVC alloc]initWithOrder:userInfo[@"order"]];
        [self.navigationController pushViewController:payVC animated:YES];
    }
    else if ([eventName isEqualToString:UF_Router_Event_OrderSure]) {
        UFOrderInfo *order = userInfo[@"order"];
        self.sureOrderID = [order.idString copy];
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"确认收货?" message:@"请收到货以后再进行确认" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
        
        
        
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        [self showHudInView:self.view hint:@"确认中..."];
        [QKHttpManager sureOrder:self.sureOrderID completion:^(NSObject *object, NSError *error){
            [self hideHud];
            if (!error) {
                if ([object isKindOfClass:[NSDictionary class]]) {
                    if ([((NSDictionary *)object)[@"code"] intValue] == QKHTTP_SUCCESS) {
                        [self.refreshControl startPullDownRefreshing];
                    }
                    
                }
            }
            
            [self showHint:httpRespString(error, object)];
            
        }];
    }
    
}

-(void)goBack{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)refreshDataSource:(int)page{
    [QKHttpManager getOrdersWithPage:page type:OrderTypeAll completion:^(NSObject *object, NSError *error){
        [self endRefresh];
        if ([object isKindOfClass:[NSDictionary class]]) {
            NSDictionary *respDic = (NSDictionary *)object;
            if ([respDic[@"code"] intValue] == QKHTTP_SUCCESS) {
                if (page == 1) {
                    self.datasource = [NSMutableArray new];
                }
                
                if (respDic[@"page"]) {
                    NSDictionary *pageDic = respDic[@"page"];
                    pageCount = [pageDic[@"pageCount"] intValue];
                    currentPage = [pageDic[@"pageNo"] intValue];
                }
                
                [self.datasource addObjectsFromArray:ordersFromArray(respDic[@"orderList"])];
                [self.showTableView reloadData];
            }
        }
    }];
}



#pragma getter
- (UITableView *)showTableView{
    if (!_showTableView) {
        _showTableView= [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height) style:UITableViewStyleGrouped];
        _showTableView.multipleTouchEnabled = YES;
        _showTableView.dataSource = self;
        _showTableView.delegate = self;
        _showTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_showTableView setBackgroundColor:[UIColor clearColor]];
        
//        [self.view addSubview:_showTableView];
    }
    
    return _showTableView;
}

- (XHRefreshControl *)refreshControl{
    if (!_refreshControl) {
        _refreshControl = [[XHRefreshControl alloc]initWithScrollView:self.showTableView delegate:self];
    }
    
    return _refreshControl;
}


#pragma mark refreshControl

/**
 *  1、这个是用于标识用户是否在加载数据中，所以涉及到业务逻辑的问题，所以就外部传值
 *
 *  @return 如果不实现该delegate方法，所有效果都会实现
 */
- (BOOL)isLoading{
    return NO;
}

/**
 *  2、将要开始下拉刷新的方法
 */
- (void)beginPullDownRefreshing{
    [self refreshDataSource:1];
}

/**
 *  3、将要开始上提加载更多的方法
 */
- (void)beginLoadMoreRefreshing{
    [self refreshDataSource:currentPage + 1];
//    [refreshControl endLoadMoreRefresing];
//    
//    messagesShowNumber += 20;
//    [self.infoTableView reloadData];
}

/**
 *  4、最后更新数据的时间
 *
 *  @return 返回缓存最后更新某个页面的时间
 */
- (NSDate *)lastUpdateTime{
    return nil;
}

/**
 *  1、是否支持下拉刷新
 *
 *  @return 如果没有实现该delegate方法，默认是支持下拉的，为YES
 */
- (BOOL)isPullDownRefreshed{
    return YES;
}

/**
 *  2、是否支持上提加载更多
 *
 *  @return 如果没有实现该delegate方法，默认是支持上提加载更多的，为YES
 */
- (BOOL)isLoadMoreRefreshed{
    return currentPage <= pageCount;
}

/**
 *  3、标识下拉刷新是UIScrollView的子view，还是UIScrollView父view的子view
 *
 *  @return 如果没有实现该delegate方法，默认是scrollView的子View，为XHRefreshViewLayerTypeOnScrollViews
 */
- (XHRefreshViewLayerType)refreshViewLayerType{
    return XHRefreshViewLayerTypeOnScrollViews;
}

/**
 *  4、UIScrollView的控制器是否保留iOS7新的特性，意思是：tablView的内容是否可以穿透过导航条
 *
 *  @return 如果不是先该delegate方法，默认是不支持的
 */
- (BOOL)keepiOS7NewApiCharacter{
    return NO;
}

/**
 *  5、将自动加载更多的状态转换为手动加载需要的条件，现在是加载更多多少次后，开始转换
 *
 *  @return 如果不实现该delegate方法，默认是5次
 */
- (NSInteger)autoLoadMoreRefreshedCountConverManual{
    return 20;
}

- (void)endRefresh{
    if (self.refreshControl) {
        [self.refreshControl endPullDownRefreshing];
        [self.refreshControl endLoadMoreRefresing];
    }
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.datasource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"OrderCell";
    OrderCell *cell = (OrderCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[OrderCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    cell.order = self.datasource[indexPath.section];
    
    return cell;
}


#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [OrderCell tableView:tableView heightForRowAtIndexPath:indexPath];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    OrderDetailVC *orderDetailVC = [[OrderDetailVC alloc]initWithOrder:self.datasource[indexPath.section]];
    [self.navigationController pushViewController:orderDetailVC animated:YES];
}


@end
